import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';
import 'package:oramemo/common/langs/text_key.dart';

class AvatarService {
  final ImagePicker _picker = ImagePicker();

  // 检查相机权限
  Future<bool> _checkCameraPermission() async {
    var status = await Permission.camera.status;
    if (status.isDenied) {
      status = await Permission.camera.request();
    }
    return status.isGranted;
  }

  // 检查相册权限
  Future<bool> _checkPhotosPermission() async {
    var status = await Permission.photos.status;
    if (status.isDenied) {
      status = await Permission.photos.request();
    }
    return status.isGranted;
  }

  // 从相机拍照
  Future<File?> takePhoto() async {
    if (!await _checkCameraPermission()) {
      throw Exception('Camera permission denied');
    }

    final XFile? photo = await _picker.pickImage(
      source: ImageSource.camera,
      preferredCameraDevice: CameraDevice.front,
      imageQuality: 80,
    );

    if (photo != null) {
      return await cropImage(File(photo.path));
    }
    return null;
  }

  // 从相册选择
  Future<File?> pickFromGallery() async {
    if (!await _checkPhotosPermission()) {
      throw Exception('Photos permission denied');
    }

    final XFile? image = await _picker.pickImage(
      source: ImageSource.gallery,
      imageQuality: 80,
    );

    if (image != null) {
      return await cropImage(File(image.path));
    }
    return null;
  }

  // 裁剪图片
  Future<File?> cropImage(File imageFile) async {
    CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: imageFile.path,
      aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: TextKey.cropAvatar.tr,
          toolbarColor: Colors.blue,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.square,
          lockAspectRatio: true,
        ),
        IOSUiSettings(
          title: TextKey.cropAvatar.tr,
          aspectRatioLockEnabled: true,
          minimumAspectRatio: 1.0,
          aspectRatioPickerButtonHidden: true,
        ),
      ],
    );

    return croppedFile != null ? File(croppedFile.path) : null;
  }
}
